package Send2ME::Create::Rule;

use Send2ME::Dao::Auth;
use Send2ME::Dao::Rule;

use Send2ME::Magic::Magic;

use Mail::RFC822::Address qw(valid);

use Dancer ':syntax';

use Switch;

prefix '/create/rule';

post '/' => sub {
	my($rule_id, $rule_uuid, $rule_name, $rule_conditions, $rule_route_in, $rule_routes) = 
		(params->{'rule_id'}, params->{'rule_uuid'}, params->{'rule_name'}, params->{'rule_conditions'}, 
		 params->{'rule_route_in'}, params->{'rule_routes'} );
	
	my $rule = {
		rule_id => params->{'rule_id'},
		rule_name => params->{'rule_name'},
		rule_conditions => params->{'rule_conditions'},
		rule_route_in => params->{'rule_route_in'},
		rule_routes => params->{'rule_routes'},
		rule_script_error => undef 
	};
	
	session $rule_uuid => $rule;
	
	unless (credential->{logged_in}) {
		redirect '/';
		return;
	}

	# check rule_route_in validity
	{
		my @routes_in = ();
		my $original = $rule_route_in;
		
		@routes_in = variables($original);
		
		unless (@routes_in) {
			redirect "/rule/?error=invalid-rule-route-in&uuid=$rule_uuid";
			return;	
		}
		
		foreach (@routes_in) {
			unless (isPerlVariableAcceptable($_)) {
				redirect "/rule/?error=invalid-rule-route-in&uuid=$rule_uuid&bad_in=$_";
				return;	
			}
		}
	}

	# check routing table validity
	{
		my $route_table = from_json( $rule_routes );
		
		unless (@{$route_table} > 0) {
			redirect "/rule/?error=empty-route-table&uuid=$rule_uuid";
			return;
		}
		
		#check recipeints to match RFC822
		my @invalid_recipients = map { 
			my $recipiet = $_->{'to'}; 
			if (!valid($recipiet)) {
				($recipiet) 
			} else {
				()
			}
		} @{$route_table};
		
		if (@invalid_recipients > 0) {
			my $invalid = join(',', @invalid_recipients);
			redirect "/rule/?error=ivalid-recipients&rcp=$invalid&uuid=$rule_uuid";
			return;
		}
	}
	
	#check validity of regex
	{
		my $conditions = from_json( $rule_conditions );
		for (@{$conditions}) {
			my $pattern = $_;
			unless (isPerlScriptAcceptable($pattern)) {
				$rule->{rule_script_error} = 
					$pattern . "<br/> Error: " . $_;
				redirect "/rule/?error=ivalid-script&uuid=$rule_uuid";
				return;
			}
		}
	}
	
	if ($rule->{rule_id}) {
		my $original = getRule({id => $rule->{rule_id}});
		
		if ($original && $original->{user_id} eq credential->{user}->{id}) {
			updateRule {
				id => $rule->{rule_id},
				user_id => $original->{user_id},
				name => $rule->{rule_name},
				conditions => $rule->{rule_conditions},
				route_in => $rule->{rule_route_in},
				routes => $rule->{rule_routes},
			};
		}
	} else {
		#ok all valid
		createRule {
			user_id => credential->{user}->{id},
			name => $rule->{rule_name},
			conditions => $rule->{rule_conditions},
			route_in => $rule->{rule_route_in},
			routes => $rule->{rule_routes},
		};
	}

	redirect "/personal/";
};

1;